﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="XmlHelper.cs" company="刘炳迪">
//  刘炳迪
// </copyright>
// <summary>
//   Defines the XmlHelper type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kaiser.Utilities
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    public class XmlHelper
    {
        private readonly XDocument xdoc;

        public XmlHelper(string path)
        {
            this.xdoc = XDocument.Load(path);
        }

        public static string GetElementAttrVal(XElement element, string attrName)
        {
            if (element != null && !string.IsNullOrEmpty(attrName))
            {
                var attr = element.Attribute(attrName);
                if (attr != null)
                {
                    return attr.Value;
                }
            }

            return string.Empty;
        }

        public IList<XElement> GetElementByParent(XElement parent)
        {
            return parent.Elements().ToList();
        }

        public XElement GetElementByAttr(string attrName, string attrValue)
        {
            var v = from i in this.xdoc.Elements()
                    let xAttribute = i.Attribute(attrName)
                    where xAttribute != null && xAttribute.Value == attrValue
                    select i;
            return v.FirstOrDefault();
        }

        public XElement GetElementByName(string name)
        {
            var v = from i in this.xdoc.Elements() where i.Name == name select i;
            return v.FirstOrDefault();
        }
    }
}
